package com.admin.boot.common.utils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import java.lang.reflect.Field;
import java.util.regex.Pattern;

/**
 * @version v3.0
 * @Description: TODO
 * @author: jeecg-boot
 * @date: 2024-01-15
 */
public class QueryGenerator {


    public static <T> QueryWrapper<T> initQueryWrapper(T entity) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        try {
            Class<?> clazz = entity.getClass();
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                String name = declaredField.getName();
                declaredField.setAccessible(true);
                Object o = declaredField.get(entity);

                if (name.equals("serialVersionUID")) {
                    continue;
                }
                //判断是否是数据库字段
                TableField tableField = declaredField.getAnnotation(TableField.class);
                if (tableField == null ) {
                    if (o !=null){
                        queryWrapper.eq(StringUtils.toLine(name), o);
                    }
                } else {
                    if (tableField.exist() && o != null) {
                        queryWrapper.eq(StringUtils.toLine(name), o);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return queryWrapper;
    }
}
